package com.risk.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.risk.login.dto.LoginUserDto;
import com.risk.login.dto.common.LoginConstant;
import com.risk.zuul.config.ConfigLogin;
import com.risk.zuul.feign.LoginService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Desc
 * @Date 2018/7/2:下午11:53
 * @Author yzMa
 * @email 2641007740@qq.com
 */
@Component
public class LoginFilter extends ZuulFilter{

    private Logger LOGGER = LoggerFactory.getLogger(LoginFilter.class);

    @Autowired
    private LoginService loginService;

    @Autowired
    private ConfigLogin configLogin;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String requestURI = request.getRequestURI();
        if(StringUtils.startsWith(requestURI,configLogin.getExcludeUrlPrefix())){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String requestURI = request.getRequestURI();

        Cookie[] cookies = request.getCookies();
        if(cookies == null || cookies.length == 0){
            LOGGER.info("run requestURI={} cookies is null",requestURI);
            sessionValidatePage();
        }
        String loginTokenWithTimeStamp = null;
        for (Cookie cookie:cookies){
            String name = cookie.getName();
            if(StringUtils.equals(name, LoginConstant.LOGIN_COOKIE_NAME)){
                loginTokenWithTimeStamp = cookie.getValue();
                break;
            }
        }
        if(StringUtils.isBlank(loginTokenWithTimeStamp)){
            LOGGER.info("run cookieVal is blank",requestURI);
            sessionValidatePage();
        }

        LoginUserDto loginUserDto = loginService.checkLoginByToken(loginTokenWithTimeStamp);
        if(loginUserDto == null){
            LOGGER.info("run loginTokenWithTimeStamp={} not exists requestURI={}",loginTokenWithTimeStamp,requestURI);
            sessionValidatePage();
        }
        loginService.updateLoginTokenTTL(loginTokenWithTimeStamp);
        return null;
    }

    private void sessionValidatePage(){
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletResponse response = requestContext.getResponse();
        try {
            response.sendRedirect(configLogin.getPage());
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
